/*
 * Created on 2005-3-25
 *
 */
package bma.common.langutil.bean.common;

import java.lang.reflect.Method;

import bma.common.langutil.core.StringUtil;

public class CommonClassDialect implements ClassDialect {

	private static CommonClassDialect instance = new CommonClassDialect();

	public static CommonClassDialect getInstance() {
		return instance;
	}

	public CommonClassDialect() {
		super();
	}

	@Override
	public PropertyMethodInfo properyMethod(Method m) {
		String name = m.getName();
		String propName = setName(name);
		if (propName != null) {
			return new PropertyMethodInfo(true, propName);
		}
		propName = getName(name);
		if (propName != null) {
			return new PropertyMethodInfo(false, propName);
		}
		propName = isName(name, m.getReturnType());
		if (propName != null) {
			return new PropertyMethodInfo(false, propName);
		}
		return null;
	}

	public static String getName(String methodName) {
		if (methodName.equals("getClass")) {
			return null;
		}
		if (methodName.startsWith("get") && methodName.length() > 3) {
			if (Character.isUpperCase(methodName.charAt(3))) {
				return StringUtil.uncap(methodName.substring(3));
			}
		}
		return null;
	}

	public static String isName(String methodName, Class type) {
		if (type == Boolean.class || type == Boolean.TYPE) {
			if (methodName.startsWith("is") && methodName.length() > 2) {
				if (Character.isUpperCase(methodName.charAt(2))) {
					return StringUtil.uncap(methodName.substring(2));
				}
			}
		}
		return null;
	}

	public static String setName(String methodName) {
		if (methodName.startsWith("set") && methodName.length() > 3) {
			if (Character.isUpperCase(methodName.charAt(3))) {
				return StringUtil.uncap(methodName.substring(3));
			}
		}
		return null;
	}

}
